<template>
  <div id="pictureManagePage">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/add_picture"
                >+ 创建图片</a-button>
<!--        空白页-->
        <a-button type="primary" href="/add_picture/batch"  ghost>+ 批量创建图片</a-button>
<!--        空白页-->
      </a-space>
    </a-flex>
    <div style="margin-bottom: 16px" />

    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介搜索"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="类型" name="category">
        <a-auto-complete
          v-model:value="searchParams.category"
          placeholder="请输入类型"
          :options="categoryOptions"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="searchParams.tags"
          mode="tags"
          placeholder="请输入标签"
          :options="tagOptions"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px" />

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="120" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'spaceId'">
          <!-- 判断 spaceId 是否为 null -->
          <span v-if="record.spaceId == null" style="text-align: center;">公共</span>
          <span v-else style="text-align: center; color: #00ff90;">私有</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <!--            通过按钮-->
            <a-popconfirm
              danger
              :disabled="record.reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS"
              title="确认通过该条数据?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
            >
              <a-button type="link" :disabled="record.reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS">
                通过
              </a-button>
            </a-popconfirm>

            <!--            拒绝按钮-->
            <a-popconfirm
              danger
              :disabled="record.reviewStatus === PIC_REVIEW_STATUS_ENUM.REJECT"
              title="确认拒绝该条数据?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >
              <a-button
                :disabled="record.reviewStatus === PIC_REVIEW_STATUS_ENUM.REJECT"
                type="link"
                danger
              >
                拒绝
              </a-button>
            </a-popconfirm>

            <!--            编辑按钮-->
            <a-button type="link" :href="`/add_picture?id=${record.id}`"
                      :disabled="record.spaceId != null"
              >编辑
            </a-button>

            <!--            删除按钮-->
            <a-popconfirm
              danger
              title="确认删除该条数据?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
              :disabled="record.spaceId != null"
            >
              <a-button
                type="link"
                :disabled="record.spaceId != null"
                danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<!--js脚本-->
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
  updatePictureUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '../../constants/picture.ts'
import { listPictureTagCategoryUsingGet } from '@/api/categoryTagController.ts'

// 控制编辑模态框的显示
const editModalVisible = ref(false)

//定义一个名叫 editPicture 的响应式对象，用来存储要编辑的图片对象的信息
let editPicture: API.Picture = reactive({
  id: 0,
  pictureAccount: '',
  pictureName: '',
  pictureAvatar: '',
  pictureProfile: '',
  pictureRole: '',
  // createTime:''
})

//分页参数
interface Page {
  current: 1
  pageSize: 10
}

//表格列
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  // {
  //   title: '图片 id',
  //   dataIndex: 'pictureId',
  //   width: 80,
  // },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作权限',
    dataIndex: 'spaceId',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化之后，重新获取数据
const doTableChange = (page: Page) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

//修改数据
// 显示编辑模态框，并填充数据
const showEditModal = (id: number) => {
  console.log('dataList', dataList.value)
  for (const key in dataList.value) {
    if (dataList.value[key].id === id) {
      editPicture = dataList.value[key]
    }
  }
  editModalVisible.value = true
}

// 处理编辑模态框的确认事件
const handleEditModalOk = () => {
  doChange(editPicture)
  editModalVisible.value = false
}

// 处理编辑模态框的取消事件
const handleEditModalCancel = () => {
  editModalVisible.value = false
}

//修改数据
const doChange = async (editPicture: API.Picture) => {
  const res = await updatePictureUsingPost(editPicture)
  if (res.data.code === 0) {
    message.success('修改成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('修改失败')
  }
}

// 删除数据
const doDelete = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败')
  }
}

//定义一个分类对象
const categoryOptions = ref<string[]>([])
//定义一个标签对象
const tagOptions = ref<string[]>([])

const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('获取标签分类列表失败，' + res.data.message)
  }
}
//钩子函数,用于首次加载页面时 调用getTagCategoryOptions函数获取:分类列表和标签列表
onMounted(() => {
  getTagCategoryOptions()
})

//审核图片（通过/拒绝）
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage =
    reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')
    // 重新获取列表
    fetchData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}
</script>
